#coding:utf-8
from django.shortcuts import render,redirect
from models import *
from hashlib import sha1
from django.http import HttpResponse,JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.core.urlresolvers import reverse #反向解析
from dd_goods.models import *

def index(request):
    type = TypeInfo.objects.all()
    # 新鲜水果初始化数据 type1点击量最高的四条 type11最新的四条
    type1 =  type[0].goodinfo_set.order_by('-gclicks')[0:4]
    type11 = type[0].goodinfo_set.order_by('-id')[0:4]

    # 海鲜水产初始化数据 type2点击量最高的四条 type21最新的四条
    type2 = type[1].goodinfo_set.order_by('-gclicks')[0:4]
    type21 = type[1].goodinfo_set.order_by('-id')[0:4]

    uname = request.session.get('uname')
    list = {'type1':type1,'type11':type11,'type2':type2,'type21':type21,'uname':uname}

    return render(request,'index.html',list)

def register(request):
    return render(request,'dd_user/register.html')

@csrf_exempt
def register_handle(request):
    # 获取注册信息
    post = request.POST
    uname = post.get('user_name')
    upwd = post.get('pwd')
    uemail = post.get('email')

    # 密码加密
    sh = sha1()
    sh.update(upwd)
    upwd1 = sh.hexdigest()

    # 创建对象
    user = UserInfo()
    user.uname = uname
    user.upwd = upwd1
    user.uemail = uemail
    user.save()

    # 注册成功之后转入登陆页面
    return redirect('/user/login/')

# 注册用户名验证是否已注册
@csrf_exempt
def register_handle_name(request):
    post = request.POST
    uname = post.get('name')
    count = UserInfo.objects.filter(uname=uname).count()
    # if count == 0:
        # 用户名可用
        # return JsonResponse({'ret':'0'})
    # else:
        # 用户名已被注册
        # return JsonResponse({'ret':'1'})
    return JsonResponse({'ret': count})

def login(request):
    return render(request,'dd_user/login.html')

# 登陆验证处理
@csrf_exempt
def login_handle(request):
    post = request.POST
    uname = post.get('username')

    userinfo = UserInfo.objects.filter(uname=uname)
    count = userinfo.count()

    if count == 0:
        # 用户查不到
        return render(request, 'dd_user/login.html',{'ret':'0'})
        # return JsonResponse({'ret':'0'})
    else:
        upwd = post.get('pwd')
        # 密码加密处理
        sh = sha1()
        sh.update(upwd)
        upwd1 = sh.hexdigest()
        # 查询集是一个字典，需要取出对应的项，再取属性值
        pwd = userinfo[0].upwd
        if upwd1 == pwd:
            # 验证通过后跳转到首页
            request.session['uname'] = uname
            return redirect('/')
        else:
            # 密码错误
            return render(request, 'dd_user/login.html', {'ret':'-1'})
            # return JsonResponse({'ret':'-1'})

# 退出
def logout(requset):
    requset.session['uname'] = None
    # return redirect("/")

    #反向解析
    return redirect(reverse('index'))

# 商品详情
# 存储最近浏览的商品
# near_goods = []
# def detail(request,id):
#     global near_goods
#     for v in near_goods:
#         if v == id:
#             near_goods.remove(id)
#     if len(near_goods) > 4:
#         near_goods.pop()
#     near_goods.insert(0, id)
#
#     print(near_goods)
#     goods = GoodInfo.objects.filter(id = id)
#     return render(request,'detail.html',{'goods':goods[0],'list':near_goods})

def detail(request,id):
    # 根据id查询数据
    goods = GoodInfo.objects.get(pk=int(id))
    # 增加点击量
    goods.gclicks = goods.gclicks+1
    goods.save()
    response = render(request,'detail.html',{'goods':goods})

    # 读取cookie
    near_goods = request.COOKIES.get('near_goods','')
    # 将id转化为字符串
    near_good_id = '%d'%goods.id # "%s 和 % d" %s是字符串对应的格式通配符，%d是数值整型对应的格式通配符

    if near_goods != '':
        near_goods1 = near_goods.split(',')
        if near_goods1.count(near_good_id)>=1:
            near_goods1.remove(near_good_id)
        near_goods1.insert(0,near_good_id)
        if len(near_goods1)>=6:
            del near_goods1[5]
        near_goods = ','.join(near_goods1) # 分隔符.join(要连接的元素序列、字符串、元组、字典)
    else:
        near_goods = near_good_id
    response.set_cookie('near_goods',near_goods)
    return response

# 用户中心
def center(request):
    uphone = UserInfo.objects.get(uname = request.session['uname']).uphone
    uname = request.session['uname']
    list = []
    near_goods = request.COOKIES.get('near_goods', '')
    near_goods1 = near_goods.split(',')
    for v in near_goods1:
        data = GoodInfo.objects.get(pk = int(v))
        list.append(data)
    return render(request,'dd_user/user_center_info.html',{'list':list,'phone':uphone,'name':uname})




